const connection = require("../app/database.js");
// 所有和数据库相关的操作
class userServer {
	async create() {
		const statement = `INSERT INTO users (username ,password )  VALUES (? , ?);`;
		const [result] = await connection.execute(statement, [null, null]);
		return result;
	}

	// 根据用户id查询用户信息
	async queryUserInfoByid(id) {
		const statement = `SELECT * FROM users WHERE id = ?;`;
		const [result] = await connection.execute(statement, [id]);
		return result[0];
	}

	// 判断是否有重复的用户名
	async queryUserByName(username) {
		const statement = `SELECT * FROM users WHERE username = ?;`;
		const [result] = await connection.execute(statement, [username]);
		return result;
	}

	// 验证用户信息是否绑定过
	async verifyBind(user_id, verify_name, verify_data) {
		const statement = `SELECT * FROM users WHERE id = ? AND ${verify_name} = ?  ;`;
		const [result] = await connection.execute(statement, [
			user_id,
			verify_data,
		]);
		return !!result.length;
	}

	// 更新用户信息
	async updateUserInfoByToken(user_id, username, password, token) {
		const statement = `UPDATE users SET username = ? , password = ? , token = ?  WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			username,
			password,
			token,
			user_id,
		]);
		return result;
	}

	// 更新用户绑定的wxopenid
	async updateUserInfoBywxOpenid ( wx_openid , user_id ) {
		const statement = `UPDATE users SET wx_openid = ?   WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			wx_openid,
			user_id,
		]);
		return result;
	}

	// 
	async verifyBindByWxopenid(wx_openid) {
		console.log(wx_openid);
		const statement = `SELECT * FROM users WHERE wx_openid = ?  ;`;
		const [result] = await connection.execute(statement, [ wx_openid ]);
		console.log(result);
		return result
	}
}
module.exports = new userServer();
